package org.jeecg.modules.yw.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.yw.entity.EnterPrise;
import org.jeecg.modules.yw.entity.Order;
import org.jeecg.modules.yw.result.Result;
import org.jeecg.modules.yw.service.EnterPriseService;
import org.jeecg.modules.yw.service.OrderService;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DateUtils;
import org.jeecg.modules.yw.utils.EncryptUtils;
import org.jeecg.modules.yw.vo.EnterPriseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/enterpriseInfo")
@Api(tags = "门窗企业管理")
public class EnterController {
    @Resource
    private EnterPriseService enterPriseService;
    @Resource
    private ISysBaseAPI sysBaseAPI;
    @Resource
    private OrderService orderService;
    @ApiOperation(value = "中控--注册审核分页")
    @GetMapping("/pageReg")
    public org.jeecg.common.api.vo.Result pageReg(@RequestParam(value = "mobile", required = false) String mobile,
                                                  @RequestParam(value = "type", required = false) String type,
                                                  @RequestParam(value = "roleid", required = false) String roleid,
                                                  @RequestParam(value = "isleader", required = false) String isleader,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<EnterPrise> queryWrapper = new LambdaQueryWrapper<>();
        if (mobile != null) {
            queryWrapper.like(EnterPrise::getMobile, mobile);
        }
        if (type != null) {
            queryWrapper.eq(EnterPrise::getApprove, type);
        }
        if (roleid != null) {
            queryWrapper.eq(EnterPrise::getRoleid, roleid);
        }
        if (isleader != null) {
            queryWrapper.eq(EnterPrise::getIsleader, isleader);
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(StringUtils.isNotBlank(area)){
                String[] areas=area.split(",");
                StringBuffer st=new StringBuffer();
                for (int i = 0; i < areas.length; i++) {
                    st.append("\""+areas[i]+"\",");
                }
                st=st.deleteCharAt(st.length()-1);
                String sql="(select id from enterprise where city_code in ("+st.toString()+") " +
                        "or (province_code in  ("+st.toString()+") and city_code is null) )";
                queryWrapper.apply("id in"+sql);
            }else{
                IPage<EnterPrise> result =new Page<>();
                return org.jeecg.common.api.vo.Result.ok(result);
            }
        }
        queryWrapper.eq(EnterPrise::getDelflag, 0);
        queryWrapper.orderByDesc(EnterPrise::getCreatetime);
        Page<EnterPrise> page = new Page<>(pageNo, pageSize);
        IPage<EnterPrise> result = enterPriseService.page(page, queryWrapper);
        return org.jeecg.common.api.vo.Result.ok(result);
    }
    @ApiOperation(value = "中控--注册企业")
    @PostMapping("/insEnterPrise")
    @ResponseBody
    public Result insEnterPrise(@RequestBody EnterPriseVo enterPriseVo) {
        if (enterPriseService.getOne(new QueryWrapper<EnterPrise>().eq("mobile", enterPriseVo.getMobile())
                .eq("delFlag", "0")) != null) {
            return Result.error("手机号已存在");
        }
        if (enterPriseService.getOne(new QueryWrapper<EnterPrise>().eq("name", enterPriseVo.getName())
                .eq("delFlag", "0")) != null) {
            return Result.error("企业已存在");
        }
        enterPriseVo.setId(CommonUtils.getID());
        enterPriseVo.setPassword(EncryptUtils.md5(CommonUtils.PWD));
        enterPriseVo.setCreatetime(DateUtils.getCurrentDate());
        enterPriseVo.setDelflag("0");//删除标识
        enterPriseVo.setApprove(1);
        enterPriseVo.setApprovetime(null);
        enterPriseVo.setRoleid(1);
        enterPriseVo.setIsleader(0);
        EnterPrise enterPrise = new EnterPrise();
        BeanUtils.copyProperties(enterPriseVo, enterPrise);
        boolean re = enterPriseService.save(enterPrise);
        if (re) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    @ApiOperation(value = "中控--企业列表页面")
    @GetMapping("/pageEnter")
    public org.jeecg.common.api.vo.Result pageEnter(@RequestParam(value = "mobile", required = false) String mobile,
                                                    @RequestParam(value = "name", required = false) String name,
                                                    @RequestParam(value = "roleid", required = false) String roleid,
                                                    @RequestParam(value = "isleader", required = false) String isleader,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<EnterPrise> queryWrapper = new LambdaQueryWrapper<>();
        if (mobile != null) {
            queryWrapper.like(EnterPrise::getMobile, mobile);
        }
        if (name != null) {
            queryWrapper.like(EnterPrise::getName, name);
        }
        if (roleid != null) {
            queryWrapper.eq(EnterPrise::getRoleid, roleid);
        }
        if (isleader != null) {
            queryWrapper.eq(EnterPrise::getIsleader, isleader);
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(StringUtils.isNotBlank(area)){
                String[] areas=area.split(",");
                StringBuffer st=new StringBuffer();
                for (int i = 0; i < areas.length; i++) {
                    st.append("\""+areas[i]+"\",");
                }
                st=st.deleteCharAt(st.length()-1);
                String sql="(select id from enterprise where city_code in ("+st.toString()+") " +
                        "or (province_code in  ("+st.toString()+") and city_code is null) )";
                queryWrapper.apply("id in"+sql);
            }else{
                IPage<EnterPrise> result =new Page<>();
                return org.jeecg.common.api.vo.Result.ok(result);
            }
        }
        queryWrapper.eq(EnterPrise::getRoleid, 1);
        queryWrapper.eq(EnterPrise::getDelflag, 0);
        queryWrapper.orderByDesc(EnterPrise::getCreatetime);
        Page<EnterPrise> page = new Page<>(pageNo, pageSize);
        IPage<EnterPriseVo> result = enterPriseService.pageEnter(page, queryWrapper);
        return org.jeecg.common.api.vo.Result.ok(result);
    }
    @ApiOperation(value = "中控--是否管理员")
    @GetMapping("/isAdmin")
    public org.jeecg.common.api.vo.Result isAdmin(@RequestParam(value = "id", required = false) String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (roleIds.contains(CommonUtils.ADMIN)) {
            return org.jeecg.common.api.vo.Result.ok(true);
        }
        return org.jeecg.common.api.vo.Result.ok(false);
    }

    @ApiOperation(value = "中控--安装班组/打胶售后人员选择(roleId: 1:门窗企业 , 2:安装人员, 3: 打胶售后 )")
    @GetMapping("/ryList")
    public List<EnterPrise> pageEnter(@RequestParam(name = "roleId", defaultValue = "2") Integer roleId,
                                      @RequestParam(name = "orderId",required = false) String orderId
                                    ) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        String[] areas=null;
        String provinceCode=null;
        String cityCode=null;
        if(StringUtils.isNotBlank(orderId)){
            Order order= orderService.getOrder(orderId);
            EnterPrise enterPrise = enterPriseService.getById(order.getCreateUserId());
            provinceCode=enterPrise.getProvinceCode();
            cityCode=enterPrise.getCityCode();
        }
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(area)){
                areas=area.split(",");
            }else{
                return new ArrayList<>();
            }
        }
        return enterPriseService.pageEnter1(orderId, roleId, areas,provinceCode,cityCode);
    }
}
